<script lang="ts" setup>
import {CopyOutlined, InboxOutlined, QuestionCircleOutlined, UserOutlined} from '@ant-design/icons-vue';
import dayjs, {Dayjs} from 'dayjs';
import {onMounted, reactive, ref, toRaw, type UnwrapRef} from 'vue';
import type {Rule} from 'ant-design-vue/es/form';
import {useInfoStore} from "@/store/user/user.ts";
import {
  addResumeAPI,
  deleteResumeByIdAPI,
  getResumeDetailByJobseekerIdAPI,
  updateResumeByIdAPI, updateResumeVerifiedAPI
} from "@/apis/resume.ts";
import {message, type UploadChangeParam, type UploadProps} from "ant-design-vue";
import type {FileType} from "ant-design-vue/es/upload/interface";
import {onBeforeRouteLeave} from "vue-router";
import {deleteImageListAPI} from "@/apis/common.ts";
import {onUnmounted} from "@vue/runtime-core";
import {addVerificationAPI} from "@/apis/verification.ts";

interface FormState {
  resumeId: string;
  resumeJobseekerId: string;
  resumeAvatar: string;
  resumeUsername: string;
  resumeGender: string;
  resumeAge: number | undefined;
  resumePhone: string;
  resumeAddress: string;
  resumeEducationSchool: string;
  resumeEducationMajor: string;
  resumeEducationDegree: string;
  resumeSchoolExperience: string;
  resumeEducationEndDate: Dayjs | undefined;
  resumeWorkExperience: string;
  resumeSkillDescription: string;
  resumeCertificatesVerified: string;
  resumeCertificates: string;
  resumePersonalProfile: string;
  resumePrivacySetting: string;
  resumeExpectedJob: string;
  resumeExpectedWorkAddress: string;
  resumeExpectedSalary: number | undefined;
  resumeExpectedSalaryType: string;
}

const formRef = ref();
const labelCol = {span: 5};
const wrapperCol = {span: 13};
const formState: UnwrapRef<FormState> = reactive({
  resumeId: "",
  resumeJobseekerId: "",
  resumeAvatar: "",
  resumeUsername: "",
  resumeGender: "",
  resumeAge: undefined,
  resumePhone: "",
  resumeAddress: "",
  resumeEducationSchool: "",
  resumeEducationMajor: "",
  resumeEducationDegree: "",
  resumeSchoolExperience: "",
  resumeEducationEndDate: undefined,
  resumeWorkExperience: "",
  resumeSkillDescription: "",
  resumeCertificatesVerified: "",
  resumeCertificates: "",
  resumePersonalProfile: "",
  resumePrivacySetting: "不公开",
  resumeExpectedJob: "",
  resumeExpectedWorkAddress: "",
  resumeExpectedSalary: undefined,
  resumeExpectedSalaryType: "",
});
const rules: Record<string, Rule[]> = {
  resumeUsername: [
    {required: true, message: '请输入你的姓名', trigger: 'change'},
  ],
  resumeGender: [
    {required: true, message: '请选择你的性别', trigger: 'change'},
  ],
  resumeAge: [
    {required: true, message: '请输入你的年龄', trigger: 'change'},
  ],
  resumePhone: [
    {required: true, message: '请输入你的联系电话', trigger: 'change'},
  ],
  resumeAddress: [
    {required: true, message: '请输入你的居住地址', trigger: 'change'},
  ],
  resumeEducationSchool: [
    {required: true, message: '请输入你的学校名称', trigger: 'change'},
  ],
  resumeEducationMajor: [
    {required: true, message: '请输入你的所学专业', trigger: 'change'},
  ],
  resumeEducationDegree: [
    {required: true, message: '请选择你的最高学历', trigger: 'change'},
  ],
  resumeEducationEndDate: [
    {required: true, message: '请选择你的毕业时间', trigger: 'change'},
  ],
};
const userStore = useInfoStore().userInfo;
const onSubmit = () => {
  formRef.value
      .validate()
      .then(async () => {
        formState.resumeJobseekerId = userStore.userId;
        console.log('values', formState, toRaw(formState));
        //除去当前头像
        if (imageList.value.length > 0) {
          imageList.value = imageList.value.slice(0, -1);
          await deleteImageListAPI(imageList.value)
        }

        if (formState.resumeId === "") {
          //添加简历
          formState.resumeCertificatesVerified = "未认证";
          const res = await addResumeAPI(formState);
          if (res.data.flag) {
            message.success('添加成功');
          } else {
            message.error('添加失败');
          }
        } else {
          //修改简历
          const res = await updateResumeByIdAPI(formState);
          if (res.data.flag) {
            message.success('修改成功');
          } else {
            message.error('修改失败');
          }
        }

      })
      .catch((error: any) => {
        console.log('error', error);
      });
};
const resetForm = () => {
  formRef.value.resetFields();
};
//生命周期
onMounted(() => {
  getResumeDetailByJobseekerId();
})

//获取简历数据
const getResumeDetailByJobseekerId = async () => {
  const res = await getResumeDetailByJobseekerIdAPI(userStore.userId);
  if (res.data.flag) {
    formState.resumeId = res.data.data.resumeId;
    formState.resumeAvatar = res.data.data.resumeAvatar;
    formState.resumeUsername = res.data.data.resumeUsername;
    formState.resumeGender = res.data.data.resumeGender;
    formState.resumeAge = res.data.data.resumeAge;
    formState.resumePhone = res.data.data.resumePhone;
    formState.resumeAddress = res.data.data.resumeAddress;
    formState.resumeEducationSchool = res.data.data.resumeEducationSchool;
    formState.resumeSchoolExperience = res.data.data.resumeSchoolExperience;
    formState.resumeEducationMajor = res.data.data.resumeEducationMajor;
    formState.resumeEducationDegree = res.data.data.resumeEducationDegree;
    formState.resumeEducationEndDate = dayjs(res.data.data.resumeEducationEndDate);
    formState.resumeSkillDescription = res.data.data.resumeSkillDescription;
    formState.resumeWorkExperience = res.data.data.resumeWorkExperience;
    formState.resumeCertificatesVerified = res.data.data.resumeCertificatesVerified;
    formState.resumeCertificates = res.data.data.resumeCertificates;
    formState.resumePersonalProfile = res.data.data.resumePersonalProfile;
    formState.resumePrivacySetting = res.data.data.resumePrivacySetting;
    formState.resumeExpectedJob = res.data.data.resumeExpectedJob;
    formState.resumeExpectedWorkAddress = res.data.data.resumeExpectedWorkAddress;
    formState.resumeExpectedSalary = res.data.data.resumeExpectedSalary;
    formState.resumeExpectedSalaryType = res.data.data.resumeExpectedSalaryType;

    //获取头像
    if (formState.resumeAvatar !== null) {
      imageUrl.value = "http://localhost:8080/image/download?name=" + formState.resumeAvatar;
    }
  }
}
//删除简历
const deleteResumeById = async () => {
  const res = await deleteResumeByIdAPI(formState.resumeId);
  if (res.data.flag) {
    message.success('删除成功');
  } else {
    message.error('删除失败');
  }
}

//设置权限
const open = ref<boolean>(false);
const showModal = () => {
  open.value = true;
};

const handleOk = (e: MouseEvent) => {
  console.log(e);
  onSubmit()
  open.value = false;
};

//设置头像
function getBase64(img: FileType | undefined, callback: (base64Url: string) => void) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
}

const fileList = ref([]);
const imageList = <any>ref([]);
const loading = ref<boolean>(false);
const imageUrl = ref<string>('');
let i = 0;
const handleChange = (info: UploadChangeParam) => {
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    // Get this url from response in real world.
    getBase64(info.file.originFileObj, (base64Url: string) => {
      imageUrl.value = base64Url;
      loading.value = false;

    });
    imageList.value.push(fileList.value[i].response.data);//照片上传记录
    formState.resumeAvatar = fileList.value[i].response.data;
    console.log("url:" + imageList.value);
    i++;
  }
  if (info.file.status === 'error') {
    loading.value = false;
    message.error('upload error');
  }
};

const beforeUpload = (file: UploadProps['fileList'][number]) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};

// 监听路由离开事件
onBeforeRouteLeave(() => {
  // 当离开当前路由时，将 imageList 发送给后端
  if (imageList.value.length > 0) {
    deleteImageListAPI(imageList.value)
        .then(() => {
          console.log('照片上传记录删除成功');
        })
        .catch((error) => {
          console.error('照片上传记录删除失败', error);
        });
  }
});
// 监听页面即将卸载事件（如刷新、关闭页面）,删除废物照片
const handleBeforeUnload = () => {
  if (imageList.value.length > 0) {
    deleteImageListAPI(imageList.value)
        .then(() => {
          console.log('照片上传记录删除成功');
        })
        .catch((error) => {
          console.error('照片上传记录删除失败', error);
        });
  }
};
onMounted(() => {
  window.addEventListener('beforeunload', handleBeforeUnload);
});
onUnmounted(() => {
  window.removeEventListener('beforeunload', handleBeforeUnload);
});

//计算颜色
const Color = (colorType: string) => {
  switch (colorType) {
    case '已认证':
      return 'green';
    case '未认证':
      return 'red';
  }
}

//提交认证
const openVerification = ref<boolean>(false);
const showModalVerification = () => {
  openVerification.value = true;
};

const handleOkVerification = (e: MouseEvent) => {
  console.log("提交了" + e);
  openVerification.value = false;
  //循环加入文件url
  formStateVerification.verificationFileList = fileListVerification.value.map((file: any) => {
    return file.response.data;
  });
  addVerificationAPI({
    verificationType: '荣誉认证',
    verificationCreaterId: userStore.userId,
    verificationCreater: userStore.userName,
    verificationStatus: '待审核',
    verificationRemarks: formStateVerification.verificationRemarks,
    verificationFileList: formStateVerification.verificationFileList,//上传的文件列表
  }).then((res: any) => {
    if (res.data.flag) {
      message.success('提交成功');
      //更改荣誉认证状态
      updateResumeVerifiedAPI({
        resumeId: formState.resumeId,
        resumeCertificatesVerified: '认证中',
      }).then((res: any) => {
        if (res.data.flag) {
          getResumeDetailByJobseekerId();
        } else {
          message.error('更改失败');
        }
      })
    } else {
      message.error('提交失败');
    }
  })
};

interface FormStateVerification {
  verificationFileList: string[];
  verificationRemarks: string;
}

const formRefVerification = ref();
const formStateVerification = reactive<FormStateVerification>({
  verificationFileList: [], //上传的文件列表
  verificationRemarks: '',
})

const fileListVerification = ref([]);
const handleChangeVerification = (info: UploadChangeParam) => {
  const status = info.file.status;
  if (status !== 'uploading') {
    console.log(info.file, info.fileList);
  }
  if (status === 'done') {
    message.success(`${info.file.name} file uploaded successfully.`);
    console.log("url:" + fileListVerification.value[0].response.data);
  } else if (status === 'error') {
    message.error(`${info.file.name} file upload failed.`);
  }
};

function handleRemove(e: DragEvent) {
  console.log('删除了', e.response.data);
}
</script>

<template>
  <div class="resume">
    <div>
      <div class="title">
        <h1 style="color: #4D7181;font-size: 30px">个人简历</h1>
        <div style="display: flex;float: right">
          <CopyOutlined class="icon" style="margin-right: 10px"/>
          <UserOutlined class="icon"/>
        </div>

      </div>
      <div class="content">
        <a-form
            ref="formRef"
            :model="formState"
            :rules="rules"
        >
          <a-divider orientation="left" style="color:#4D7181; font-size: 20px">基本信息</a-divider>
          <div class="basic">
            <div class="basicInfo">
              <a-form-item ref="resumeUsername" label="姓名" name="resumeUsername">
                <a-input v-model:value="formState.resumeUsername" style="width: 100px;"/>
              </a-form-item>
              <a-form-item ref="resumeAge" label="年龄" name="resumeAge">
                <a-input-number v-model:value="formState.resumeAge" style="width: 100px;"/>
              </a-form-item>
              <a-form-item ref="resumeGender" label="性别" name="resumeGender">
                <a-select v-model:value="formState.resumeGender" style="width: 100px;">
                  <a-select-option value="男">男</a-select-option>
                  <a-select-option value="女">女</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item ref="resumePhone" label="联系电话" name="resumePhone">
                <a-input v-model:value="formState.resumePhone" style="width: 300px;"/>
              </a-form-item>
              <a-form-item ref="resumeAddress" label="居住地址" name="resumeAddress">
                <a-input v-model:value="formState.resumeAddress" style="width: 300px;"/>
              </a-form-item>
            </div>
            <div class="update">
              <a-upload
                  v-model:file-list="fileList"
                  :before-upload="beforeUpload"
                  :show-upload-list="false"
                  action="http://localhost:8080/image/upload"
                  class="avatar-uploader"
                  list-type="picture-card"
                  name="file"
                  @change="handleChange"

              >
                <img v-if="imageUrl" :src="imageUrl" alt="avatar" style="width: 120px; height: 150px;"/>
                <div v-else>
                  <loading-outlined v-if="loading"></loading-outlined>
                  <plus-outlined v-else></plus-outlined>
                  <div class="ant-upload-text">上传照片</div>
                </div>
              </a-upload>
            </div>
          </div>
          <a-divider orientation="left" style="color:#4D7181; font-size: 20px">教育背景</a-divider>
          <div class="school">
            <a-form-item ref="resumeEducationSchool" label="学校名称" name="resumeEducationSchool">
              <a-input v-model:value="formState.resumeEducationSchool" style="width: 180px; "/>
            </a-form-item>
            <a-form-item ref="resumeEducationMajor" label="所学专业" name="resumeEducationMajor"
                         style="margin-left: 50px">
              <a-input v-model:value="formState.resumeEducationMajor" style="width: 180px; "/>
            </a-form-item>
          </div>
          <div class="school">
            <a-form-item ref="resumeEducationDegree" label="最高学历" name="resumeEducationDegree">
              <a-select v-model:value="formState.resumeEducationDegree" placeholder="请选择最高学历！"
                        style="width: 180px;">
                <a-select-option value="大专">大专</a-select-option>
                <a-select-option value="本科">本科</a-select-option>
                <a-select-option value="硕士">硕士</a-select-option>
                <a-select-option value="博士">博士</a-select-option>
                <a-select-option value="其他">其他</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item ref="resumeEducationEndDate" label="毕业时间" name="resumeEducationEndDate"
                         style="margin-left: 50px">
              <a-date-picker v-model:value="formState.resumeEducationEndDate" style="width: 180px;"/>
            </a-form-item>
          </div>

          <div class="school">
            <a-form-item ref="resumeSchoolExperience" label="校园经历"
                         name="resumeSchoolExperience">
              <a-textarea v-model:value="formState.resumeSchoolExperience"
                          :auto-size="{minRows: 4, maxRows: 10}"
                          :maxlength="300"
                          show-count
                          style="width: 600px"
              />
            </a-form-item>
          </div>

          <div class="school">
            <a-badge-ribbon :color="Color(formState.resumeCertificatesVerified)"
                            :text="formState.resumeCertificatesVerified">
              <a-form-item ref="resumeCertificates" label="荣誉奖项"
                           name="resumeCertificates">
                <a-textarea v-model:value="formState.resumeCertificates"
                            :auto-size="{minRows: 4, maxRows: 10}"
                            :maxlength="300"
                            show-count
                            style="width: 600px"
                />
              </a-form-item>

            </a-badge-ribbon>
          </div>

          <a-divider orientation="left" style="color:#4D7181; font-size: 20px">技能特长</a-divider>
          <div class="school">
            <a-form-item ref="resumeSkillDescription" label="技能特长"
                         name="resumeSkillDescription">
              <a-textarea v-model:value="formState.resumeSkillDescription"
                          :auto-size="{minRows: 4, maxRows: 10}"
                          :maxlength="300"
                          show-count
                          style="width: 600px"
              />
            </a-form-item>
          </div>
          <a-divider orientation="left" style="color:#4D7181; font-size: 20px">工作经历</a-divider>
          <div class="school">
            <a-form-item ref="resumeWorkExperience" label="工作经历"
                         name="resumeWorkExperience">
              <a-textarea v-model:value="formState.resumeWorkExperience"
                          :auto-size="{minRows: 4, maxRows: 10}"
                          :maxlength="300"
                          show-count
                          style="width: 600px"
              />
            </a-form-item>
          </div>
          <a-divider orientation="left" style="color:#4D7181; font-size: 20px">自我介绍</a-divider>
          <div class="school">
            <a-form-item ref="resumePersonalProfile" label="自我介绍"
                         name="resumePersonalProfile">
              <a-textarea v-model:value="formState.resumePersonalProfile"
                          :auto-size="{minRows: 4, maxRows: 10}"
                          :maxlength="300"
                          show-count
                          style="width: 600px"
              />
            </a-form-item>
          </div>
          <a-divider orientation="left" style="color:#4D7181; font-size: 20px">工作期望</a-divider>
          <div class="school">
            <a-form-item ref="resumeExpectedJob" label="期望职位" name="resumeExpectedJob">
              <a-input v-model:value="formState.resumeExpectedJob" style="width: 180px; "/>
            </a-form-item>
            <a-form-item ref="resumeExpectedSalary" label="期望薪资" name="resumeExpectedSalary"
                         style="margin-left: 50px">
              <a-input-number v-model:value="formState.resumeExpectedSalary" style="width: 180px; "/>
            </a-form-item>

          </div>
          <div class="school">
            <a-form-item ref="resumeExpectedSalaryType" label="期望薪资类型" name="resumeExpectedSalaryType"
                         style="margin-left: 50px">
              <a-select v-model:value="formState.resumeExpectedSalaryType" style="width: 100px;">
                <a-select-option value="时薪">时薪</a-select-option>
                <a-select-option value="日薪">日薪</a-select-option>
                <a-select-option value="月薪">月薪</a-select-option>
                <a-select-option value="均可">均可</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item ref="resumeExpectedWorkAddress" label="期望工作地点" name="resumeExpectedWorkAddress"
                         style="margin-left: 50px">
              <a-input v-model:value="formState.resumeExpectedWorkAddress" style="width: 180px; "/>
            </a-form-item>
          </div>

          <div class="school" style="display: flex; justify-content: flex-end; margin-right: 20px">
            <div>
              <a-modal v-model:open="open" cancelText="取消" okText="确认" title="设置-简历权限" @ok="handleOk">
                <a-radio-group v-model:value="formState.resumePrivacySetting" button-style="solid">
                  <a-radio-button style="width: 200px;text-align: center" value="公开">公开</a-radio-button>
                  <a-radio-button style="width: 200px;text-align: center" value="不公开">不公开-(仅自己和雇主)
                  </a-radio-button>
                </a-radio-group>
              </a-modal>
            </div>
            <div
                style="border: 2px solid #1E80FF;
                 padding: 25px;
                 border-radius: 20px;
                 display: flex;
                 align-items: center;
                 justify-items: center"
            >
              <a-button ghost style="margin-right: 20px" type="primary" @click="onSubmit">保存提交</a-button>
              <a-button danger ghost style="margin-right: 20px" type="primary" @click="resetForm">重置表单</a-button>
              <a-popconfirm cancelText="取消" okText="确认" title="你确定删除简历吗？" @confirm="deleteResumeById ">
                <template #icon>
                  <question-circle-outlined style="color: red"/>
                </template>
                <a-button danger style="margin-right: 20px" type="primary">删除简历</a-button>
              </a-popconfirm>
              <a-button style="margin-right: 20px" type="primary" @click="showModal">设置权限</a-button>
              <a-button v-if="formState.resumeCertificatesVerified==='未认证'"
                        style="color: white;background-color: #67C23A;margin-right: 20px"
                        @click="showModalVerification">认证荣誉
              </a-button>


              <!--          认证弹窗-->
              <div>
                <a-modal v-model:open="openVerification"
                         cancel-text="取消-认证"
                         ok-text="确认-提交认证"
                         title="荣誉-认证"
                         @ok="handleOkVerification">
                  <div style="width: 400px">
                    <a-form
                        ref="formRefVerification"
                        :label-col="labelCol"
                        :model="formStateVerification"
                        :wrapper-col="wrapperCol"
                    >
                      <a-form-item label="认证要求">
                    <span
                        style="display: block;width: 400px"
                    >
                      荣誉认证要求，需要上传相关的荣誉证书
                    </span>
                      </a-form-item>
                      <a-form-item label="认证备注" name="verificationRemarks">
                        <a-textarea v-model:value="formStateVerification.verificationRemarks"
                                    :auto-size="{minRows: 2, maxRows: 10}"
                                    :maxlength="300"
                                    show-count
                                    style="width: 300px"/>
                      </a-form-item>
                      <a-form-item label="认证文件" name="verificationFileList">
                        <a-upload-dragger
                            v-model:fileList="fileListVerification"
                            :multiple="true"
                            action="http://localhost:8080/file/upload"
                            name="file"
                            style="width: 400px"
                            @change="handleChangeVerification"
                            @remove="handleRemove"
                        >
                          <p class="ant-upload-drag-icon">
                            <inbox-outlined></inbox-outlined>
                          </p>
                          <p class="ant-upload-text">单击或拖动文件到此区域上传</p>
                          <p class="ant-upload-hint">
                            支持单次或批量上传!
                          </p>
                        </a-upload-dragger>


                      </a-form-item>
                    </a-form>
                  </div>
                </a-modal>
              </div>
            </div>
          </div>

        </a-form>
      </div>
    </div>
  </div>

</template>

<style scoped>
.resume {
  max-width: 900px;
  margin: 5px;
  padding: 20px 60px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1);
  border-radius: 20px; /* 你可以调整这个值来改变圆角的大小 */
  background-color: white;

  .title {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .icon {
      font-size: 35px;
      padding: 15px;
      color: white;
      background-color: #C09E66;
      border-radius: 50px;
      margin-bottom: 10px;
    }
  }

  .content {
    border: 2px solid #4D7181;
    padding: 20px;
    border-top: 20px solid #4D7181;
    border-radius: 10px;

    .basic {
      display: flex;
      padding-left: 30px;
      justify-content: space-between;

      .basicInfo {
        width: 70%;
        height: 100%;
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap; /* 允许子元素换行 */
        gap: 0 30px; /* 设置水平间距为10px，垂直间距为0 */
      }

      .update {
        width: 120px;
        height: 150px;
        margin-right: 60px;
      }
    }

    .school {
      display: flex;
      padding-left: 30px;
    }
  }
}
</style>
